package com.baic.ibase.service.devices.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baic.ibase.controller.BusinessException;
import com.baic.ibase.mapper.DeviceMessageLogMapper;
import com.baic.ibase.mapper.DevicesMapper;
import com.baic.ibase.models.dao.DeviceMessageLog;
import com.baic.ibase.models.dao.Devices;
import com.baic.ibase.models.req.devices.ExecuteCommandReq;
import com.baic.ibase.service.devices.DeviceService;
import com.baic.ibase.service.mqtt.MqttSendService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DevicesMapper, Devices> implements DeviceService {

    @Autowired
    private DevicesMapper devicesMapper;
    @Autowired
    private DeviceMessageLogMapper deviceMessageLogMapper;
    @Autowired
    private MqttSendService mqttSendService;


    @Override
    public Boolean executeCommand(ExecuteCommandReq req) {

        Devices devices = devicesMapper.selectById(req.getDeviceId());
        if (devices == null) {
            throw new BusinessException("设备不存在");
        }

        if (devices.getDeviceConnectionStatus() == 0) {
            throw new BusinessException("设备未连接");
        }

        // 写日志
        DeviceMessageLog deviceMessageLog = new DeviceMessageLog();
        deviceMessageLog.setRequestId(req.getRequestId());
        deviceMessageLog.setDeviceName(devices.getDeviceName());
        deviceMessageLog.setDeviceId(devices.getDeviceId());
        deviceMessageLog.setDeviceCommand(req.getCommand());
        deviceMessageLog.setDeviceCommandParam(req.getCommandParam());
        deviceMessageLog.setCreatedUserId(req.getUserId());
        deviceMessageLog.setUpdatedUserId(1L);
        deviceMessageLog.setUserId(req.getUserId());
        deviceMessageLogMapper.insert(deviceMessageLog);

        // todo: 重试
        String topic = "/ibase-device/" + devices.getProductId() + "/" + devices.getDeviceId() + "/service/command";
        JSONObject newCommandParam = new JSONObject();
        newCommandParam.put("command", req.getCommand().getValue());
        newCommandParam.put("deviceId", devices.getDeviceId());
        newCommandParam.put("productId", devices.getProductId());
        newCommandParam.put("requestId", req.getRequestId());
        newCommandParam.put("messageId", deviceMessageLog.getId());
        newCommandParam.put("commandParam", req.getCommandParam());
        mqttSendService.send(topic, 1,  newCommandParam.toJSONString());

        return true;
    }

    @Override
    public void connected(JSONObject jsonObject) {
        // 更新设备状态、属性
        log.info("connected:{}", jsonObject);
        Long deviceId = jsonObject.getLong("deviceId");
        Long productId = jsonObject.getLong("productId");
        String deviceOs = jsonObject.getString("deviceOs");
        String deviceOsVersion = jsonObject.getString("deviceOsVersion");
        String deviceClientType = jsonObject.getString("deviceClientType");
        String deviceClientVersion = jsonObject.getString("deviceClientVersion");
        String deviceMac = jsonObject.getString("deviceMac");
        String deviceType = jsonObject.getString("deviceType");
        String deviceIp = jsonObject.getString("deviceIp");
        String deviceClientId = jsonObject.getString("deviceClientId");

        Devices devices = devicesMapper.selectById(deviceId);
        devices.setDeviceClientType(deviceClientType);
        devices.setDeviceClientVersion(deviceClientVersion);
        devices.setDeviceIp(deviceIp);
        devices.setDeviceMac(deviceMac);
        devices.setDeviceOsVersion(deviceOsVersion);
        devices.setDeviceOs(deviceOs);
        devices.setDeviceClientId(deviceClientId);
        devices.setDeviceConnectionStatus(1);
        devices.setLastConnectTime(LocalDateTime.now());
        devicesMapper.updateById(devices);

    }

    @Override
    public void disconnected(JSONObject jsonObject) {
        Long deviceId = jsonObject.getLong("deviceId");

        Devices devices = devicesMapper.selectById(deviceId);
        devices.setDeviceConnectionStatus(0);

        devicesMapper.updateById(devices);

    }


    @Override
    public void commandAck(JSONObject jsonObject) {
        // 设置消息状态为已读
        Long messageId = jsonObject.getLong("messageId");
        String status = jsonObject.getString("status");
        DeviceMessageLog deviceMessageLog = deviceMessageLogMapper.selectById(messageId);

        deviceMessageLog.setStatus(status);
        deviceMessageLogMapper.updateById(deviceMessageLog);
    }

    @Override
    public void commandResponse(JSONObject jsonObject) {
        // 更新命令执行结果
        Long messageId = jsonObject.getLong("messageId");
        String status = jsonObject.getString("status");
        Long deviceId = jsonObject.getLong("deviceId");
        Long productId = jsonObject.getLong("productId");
        JSONObject result = jsonObject.getJSONObject("result");

        DeviceMessageLog deviceMessageLog = deviceMessageLogMapper.selectById(messageId);

        deviceMessageLog.setStatus(status);
        deviceMessageLog.setDeviceCommandResponse(result);
        deviceMessageLogMapper.updateById(deviceMessageLog);
    }

    @Override
    public void proxyExecuteCommand(JSONObject jsonObject) {

    }
}
